package com.icart.controller.personController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icart.context.HttpUserContext;
import com.icart.context.provider.UserContextProvider;
import com.icart.context.storage.ContextStorage;
import com.icart.context.storage.SessionContextStorageImpl;
import com.icart.controller.HomeController;
import com.icart.repositories.CarBrandRepository;
import com.icart.repositories.CustcarRepository;
import com.icart.repositories.CustinfoRepository;
import com.icart.util.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Controller
@RequestMapping("/person")
public class MycarController {

    @Autowired
    CustinfoRepository custinfoRepository;
    @Autowired
    CarBrandRepository carBrandRepository;
    @Autowired
    CustcarRepository custcarRepository;
    @Autowired
    HttpServletRequest request;
    @Autowired
    private RestTemplate template;

    /*车型首页*/
    @RequestMapping("/carhome")
    public String carhome(@RequestParam(name = "custcarid",required = false) Long custcarid,Model model){
        ContextStorage storage=new SessionContextStorageImpl(request);
        HttpUserContext userContext=storage.getUserContext("loginuser");

        /*获取微信的token*/
        String url="http://pay.wechat.ikartek.com/jssdk/api.php?url=http://testwx.ikartek.com/person/carhome&token=";
        HomeController.gettoken(model,template,url,request);

        List list=null;
        if(custcarid==null){
            /*查出设为默认车辆的信息*/
            String sql="select r.custcarid,r.carno,(select d.brandname from bi_carbrand d where d.brandid=f.brandid)brandname," +
                    "(select e.carlinename from bi_carline e where e.carlineid=f.carlineid)carlinename,f.carvol,f.caryear,(select brandlogo from bi_carbrand where brandid=f.brandid)brandlogo," +
                    "r.regdate,r.setdefault,r.curkilo,r.engineno,r.vin,(select y.insucomname from cu_insucompany y where y.insucomid=r.insucomid)insucomname," +
                    "r.insuexpirydate,r.regionid " +
                    "from cu_custcar r,bi_cardef f where r.cartype=f.cartypeid and r.setdefault=1 and r.custid="+userContext.getCustid();
            list=custcarRepository.createNativeQuery(sql);
        }else {
            /*查出设为默认车辆的信息*/
            String sql="select r.custcarid,r.carno,(select d.brandname from bi_carbrand d where d.brandid=f.brandid)brandname," +
                    "(select e.carlinename from bi_carline e where e.carlineid=f.carlineid)carlinename,f.carvol,f.caryear,(select brandlogo from bi_carbrand where brandid=f.brandid)brandlogo," +
                    "r.regdate,r.setdefault,r.curkilo,r.engineno,r.vin,(select y.insucomname from cu_insucompany y where y.insucomid=r.insucomid)insucomname," +
                    "r.insuexpirydate,r.regionid " +
                    "from cu_custcar r,bi_cardef f where r.cartype=f.cartypeid and r.custcarid="+custcarid+" and r.custid="+userContext.getCustid();
            list=custcarRepository.createNativeQuery(sql);
        }
        if(list.size()>0){
            model.addAttribute("car",list.get(0));

        /*查出车牌的省份*/
            String sql2="select dictname from sa_db_dictitem where groupid='BI_CARNOHEAD'";
            List list2=custcarRepository.createNativeQuery(sql2);
            model.addAttribute("province",list2);

        /*查出保险公司*/
            String sql3="select * from cu_insucompany";
            List list3=custcarRepository.createNativeQuery(sql3);
            model.addAttribute("insucompany",list3);
            return "person/cartype/cartypehome";
        }else {
            return "redirect:/person/addcar";
        }

    }

    /*微信服务器下载图片转base64*/
    @RequestMapping("/uploadpic")
    @ResponseBody
    public String uploadpic(@RequestParam(name = "mediaId",required = false) String mediaId,Model model){
        String base64=HomeController.getPic(mediaId,template,request);
        return base64;
    }
   /*行驶证拍照*/
    @RequestMapping("/getLocalImgData")
    public String getLocalImgData(@RequestParam(name = "json",required = false) String json,
                                  @RequestParam(name = "custcarid",required = false) String custcarid,@RequestParam(name = "setdefault",required = false) String setdefault,Model model){
        JSONObject jsonObject=JSON.parseObject(json);
        JSONArray object=jsonObject.getJSONObject("data").getJSONArray("outputs");
        String dataValue= object.getJSONObject(0).getJSONObject("outputValue").getString("dataValue");
        JSONObject content=JSON.parseObject(dataValue);

        String vin = content.getString("vin");
        model.addAttribute("vin",vin);
        String owner = content.getString("owner");
        model.addAttribute("owner",owner);
        String issue_date = content.getString("issue_date");
        issue_date=issue_date.substring(0,4)+"-"+issue_date.substring(4,6)+"-"+issue_date.substring(6,8);
        model.addAttribute("issue_date",issue_date);/*发证时间*/
        String register_date = content.getString("register_date");
        register_date=register_date.substring(0,4)+"-"+register_date.substring(4,6)+"-"+register_date.substring(6,8);
        model.addAttribute("register_date",register_date);/*注册时间*/
        String model2 = content.getString("model");
        model.addAttribute("model",model2);/*品牌*/
        String plate_num = content.getString("plate_num");
        model.addAttribute("plate_num",plate_num);
        String engine_num = content.getString("engine_num");
        model.addAttribute("engine_num",engine_num);

        model.addAttribute("custcarid",custcarid);
        model.addAttribute("setdefault",setdefault);/*传给后面判断是不是设为默认车辆，如果是，就修改用户名*/
        return "person/cartype/ocrcar";
    }

    /*保存传回来的行驶证的信息*/
    @RequestMapping("/saveocrcarinfo")
    @ResponseBody
    public String saveocrcarinfo(){
        ContextStorage storage=new SessionContextStorageImpl(request);
        HttpUserContext userContext=storage.getUserContext("loginuser");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date1=null;
        Date date2=null;

        String owner=request.getParameter("owner");
        String plate_num=request.getParameter("plate_num");
        String model=request.getParameter("model");
        String vin=request.getParameter("vin");
        String engine_num=request.getParameter("engine_num");
        String register_date= request.getParameter("register_date");
        String issue_date=request.getParameter("issue_date");
        try {
            date1 = sdf.parse(register_date);
            date2 = sdf.parse(issue_date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Long custcarid=Long.parseLong(request.getParameter("custcarid"));
        Long setdefault=Long.parseLong(request.getParameter("setdefault"));

        custcarRepository.saveocr(plate_num,model,vin,engine_num,date1,date2,custcarid,userContext.getCustid());
        if (setdefault==1){
            Integer isflag=custinfoRepository.updatecustname(owner,userContext.getCustid());

            if (isflag>0){
                HttpUserContext context= UserContextProvider.create(userContext.getCustid(),owner);
                storage.clear("loginuser");
                storage.save("loginuser",context);
            }
        }
        return "success";
    }
    /*我的车型*/
    @RequestMapping("/mycar")
    public String mycar(Model model){
        ContextStorage storage=new SessionContextStorageImpl(request);
        HttpUserContext userContext=storage.getUserContext("loginuser");

        String sql="select r.custcarid,(select d.brandname from bi_carbrand d where d.brandid=f.brandid)brandname,(select brandlogo from bi_carbrand where brandid=f.brandid)brandlogo," +
                "(select e.carlinename from bi_carline e where e.carlineid=f.carlineid)carlinename,f.carvol,f.caryear,r.regdate,r.setdefault " +
                "from cu_custcar r,bi_cardef f where r.cartype=f.cartypeid and r.custid="+userContext.getCustid()+" order by r.setdefault desc";
        List list=custcarRepository.createNativeQuery(sql);
        model.addAttribute("car",list);
        return "person/cartype/mycar";
    }

    /*新增车型*/
    @RequestMapping("/addcar")
    public String addcar(Model model){
        /*查出热门品牌*/
        List hotbrand=carBrandRepository.createNativeQuery("select * from bi_carbrand where ishot=1");
        model.addAttribute("hotbrand",hotbrand);


        /*查出ABCD..字母*/
        List firstchar=carBrandRepository.createNativeQuery("select firstchar from bi_carbrand group by firstchar order by firstchar");
        model.addAttribute("firstchar",firstchar);

        /*查出所有的品牌，再在前台判断*/
        List carbrand=carBrandRepository.createNativeQuery("select * from bi_carbrand order by firstchar");
        model.addAttribute("carbrand",carbrand);
        if(Tools.notEmpty(request.getParameter("flag"))) {
            model.addAttribute("flag", request.getParameter("flag"));
            model.addAttribute("busiid", request.getParameter("busiid"));
            model.addAttribute("shopid", request.getParameter("shopid"));
        }
       return "person/cartype/addcar";
    }

    /*查出所选品牌对应下的车系*/
    @RequestMapping("/choosecarline")
    public String choosecarlinev(@RequestParam(name = "carbrand",required = false) String carbrand,@RequestParam(name = "brandname",required = false) String brandname, Model model){
        /*先查出车厂名字*/
        List carfactory=carBrandRepository.createNativeQuery("select y.carfactid,y.carfactname from bi_carline e,bi_carfactory y " +
                "where e.carfactid=y.carfactid and e.brandid='"+carbrand+"' group by e.carfactid");
        model.addAttribute("carfactory",carfactory);

        /*查出车厂对应下的车系*/
        List carline=carBrandRepository.createNativeQuery("select carlineid,carlinename,carfactid from bi_carline where brandid='"+carbrand+"'");
        model.addAttribute("carline",carline);

        /*设置头*/
        model.addAttribute("brandname",brandname);
        model.addAttribute("carbrand",carbrand);

        if(Tools.notEmpty(request.getParameter("flag"))) {
            model.addAttribute("flag", request.getParameter("flag"));
            model.addAttribute("busiid", request.getParameter("busiid"));
            model.addAttribute("shopid", request.getParameter("shopid"));
        }
        return "person/cartype/choosecarline";
    }

    /*选完车系后选排量*/
    @RequestMapping("/choosecarvol")
    public String choosecarvol(@RequestParam(name = "carlineid",required = false) String carlineid,@RequestParam(name = "carbrand",required = false) String carbrand,Model model)
    {
        List carvol=carBrandRepository.createNativeQuery("select carvol from bi_cardef where carlineid='"+carlineid+"' group by carvol");
        model.addAttribute("carvol",carvol);
        model.addAttribute("carlineid",carlineid);
        model.addAttribute("carbrand",carbrand);

        if(Tools.notEmpty(request.getParameter("flag"))) {
            model.addAttribute("flag", request.getParameter("flag"));
            model.addAttribute("busiid", request.getParameter("busiid"));
            model.addAttribute("shopid", request.getParameter("shopid"));
        }
        return "person/cartype/choosecarvol";
    }
    /*选完排量后选年份*/
    @RequestMapping("/choosecaryear")
    public String choosecaryear(@RequestParam(name = "carlineid",required = false) String carlineid,@RequestParam(name = "carbrand",required = false) String carbrand,
                                @RequestParam(name = "carvol",required = false) String carvol,Model model)
    {
        List caryear=carBrandRepository.createNativeQuery("select caryear from bi_cardef where carlineid='"+carlineid+"' and carvol='"+carvol+"'");
        model.addAttribute("caryear",caryear);
        model.addAttribute("carvol",carvol);
        model.addAttribute("carlineid",carlineid);
        model.addAttribute("carbrand",carbrand);

        if(Tools.notEmpty(request.getParameter("flag"))) {
            model.addAttribute("flag", request.getParameter("flag"));
        }
        if(Tools.notEmpty(request.getParameter("busiid"))) {
            model.addAttribute("busiid", request.getParameter("busiid"));
        }
        if(Tools.notEmpty(request.getParameter("shopid"))) {
            model.addAttribute("shopid", request.getParameter("shopid"));
        }
        return "person/cartype/choosecaryear";
    }

    /*选完以后开始插入数据库*/
    @RequestMapping("/increasecar")
    public String increasecar(@RequestParam(name = "carlineid",required = false) String carlineid,@RequestParam(name = "carbrand",required = false) String carbrand,
                                @RequestParam(name = "carvol",required = false) String carvol,@RequestParam(name = "caryear",required = false) String caryear,Model model)
    {
        ContextStorage storage=new SessionContextStorageImpl(request);
        HttpUserContext userContext=storage.getUserContext("loginuser");

        List cardef=carBrandRepository.createNativeQuery("select cartypeid,cartypename from bi_cardef where brandid='"+carbrand+"' and carlineid='"+carlineid+
                "' and carvol='"+carvol+"' and caryear='"+caryear+"'");
        String cardef2=JSON.toJSONString(cardef);
        cardef2=cardef2.replace("[", "");
        cardef2=cardef2.replace("]", "");
        JSONObject cardef3 = JSON.parseObject(cardef2);//将list转换为json对象
        List list=new ArrayList();
        if(userContext!=null) {
             list = custcarRepository.createNativeQuery("select * from cu_custcar where custid=" + userContext.getCustid());
            if(list.size()==0){
                String cartypeid=cardef3.getString("cartypeid");
                custcarRepository.firstinsert(userContext.getCustid(),cartypeid);
            }else {
                String cartypeid=cardef3.getString("cartypeid");
                custcarRepository.insert(userContext.getCustid(),cartypeid);
            }
        }
        /*判断是不是第一个车型，如果是就默认*/
        String flag2 ="";
        if(Tools.notEmpty(request.getParameter("flag"))) {
            flag2=request.getParameter("flag");
        }
        if (flag2.equals("1")) {
            if(Tools.notEmpty(request.getParameter("busiid"))) {
                String busiid = request.getParameter("busiid");
    //                request.setAttribute("busiid",busiid);
                return "redirect:/item/item?busiid=" + busiid;
            }
        }
        if(flag2.equals("2")){
            if(Tools.notEmpty(request.getParameter("shopid"))) {
                String chnid =request.getParameter("shopid");
    //                request.setAttribute("chnid",chnid);
                return "redirect:/shopdetail?chnid="+chnid;
            }
        }
        if(flag2.equals("3")){
            return "redirect:/sale/create?cartype="+cardef3.getString("cartypeid");
        }
        return "redirect:/person/mycar";
    }

    /*删除车系*/
    @RequestMapping("/deletecar")
    public String deletecar(@RequestParam(name = "custcarid",required = false) Long custcarid,Model model)
    {
        ContextStorage storage=new SessionContextStorageImpl(request);
        HttpUserContext userContext=storage.getUserContext("loginuser");

        Integer flag=custcarRepository.delete(custcarid,userContext.getCustid());
        if(flag==1){
            return "redirect:/person/mycar";
        }else {
            return "redirect:/person/mycar";
        }
    }

    /*车系设为默认*/
    @RequestMapping("/setdefault")
    @ResponseBody
    public String setdefault(@RequestParam(name = "custcarid",required = false) Long custcarid,Model model)
    {
        ContextStorage storage=new SessionContextStorageImpl(request);
        HttpUserContext userContext=storage.getUserContext("loginuser");

        Integer flag=custcarRepository.setdefault(userContext.getCustid());
        Integer flag2=custcarRepository.setdefault2(userContext.getCustid(),custcarid);
       if(flag>0&&flag2>0){
            return "success";
       }else {
           return "fail";
       }
    }

    /*输入车牌号ajax存储*/
    @RequestMapping("/savecarno")
    @ResponseBody
    public String savecarno(@RequestParam(name = "carno",required = false) String carno,
                            @RequestParam(name = "custcarid",required = false) Long custcarid,Model model)
    {
        ContextStorage storage=new SessionContextStorageImpl(request);
        HttpUserContext userContext=storage.getUserContext("loginuser");

        Integer flag=custcarRepository.savecarno(carno,custcarid,userContext.getCustid());
        if(flag>0){
            return "success";
        }else {
            return "fail";
        }
    }
    /*输入发动机号ajax存储*/
    @RequestMapping("/saveengineno")
    @ResponseBody
    public String saveengineno(@RequestParam(name = "saveengineno",required = false) String saveengineno,
                               @RequestParam(name = "custcarid",required = false) Long custcarid,Model model)
    {
        ContextStorage storage=new SessionContextStorageImpl(request);
        HttpUserContext userContext=storage.getUserContext("loginuser");

        Integer flag=custcarRepository.saveengineno(saveengineno,custcarid,userContext.getCustid());
        if(flag>0){
            return "success";
        }else {
            return "fail";
        }
    }

    /*输入车架号（vin）ajax存储*/
    @RequestMapping("/savevin")
    @ResponseBody
    public String savevin(@RequestParam(name = "vin",required = false) String vin,
                          @RequestParam(name = "custcarid",required = false) Long custcarid,Model model)
    {
        ContextStorage storage=new SessionContextStorageImpl(request);
        HttpUserContext userContext=storage.getUserContext("loginuser");

        Integer flag=custcarRepository.savevin(vin,custcarid,userContext.getCustid());
        if(flag>0){
            return "success";
        }else {
            return "fail";
        }
    }

    /*输入保险到期日ajax存储*/
    @RequestMapping("/saveinsuexpirydate")
    @ResponseBody
    public String saveinsuexpirydate(@RequestParam(name = "insuexpirydate",required = false) String insuexpirydate,
                                     @RequestParam(name = "custcarid",required = false) Long custcarid,Model model)
    {
        ContextStorage storage=new SessionContextStorageImpl(request);
        HttpUserContext userContext=storage.getUserContext("loginuser");

        Integer flag=custcarRepository.saveinsuexpirydate(insuexpirydate,custcarid,userContext.getCustid());
        if(flag>0){
            return "success";
        }else {
            return "fail";
        }
    }

    /*输入保险公司ajax存储*/
    @RequestMapping("/saveinsucomname")
    @ResponseBody
    public String saveinsucomname(@RequestParam(name = "insucomid",required = false) Long insucomid,
                                  @RequestParam(name = "custcarid",required = false) Long custcarid,Model model)
    {
        ContextStorage storage=new SessionContextStorageImpl(request);
        HttpUserContext userContext=storage.getUserContext("loginuser");

        Integer flag=custcarRepository.saveinsucomname(insucomid,custcarid,userContext.getCustid());
        if(flag>0){
            return "success";
        }else {
            return "fail";
        }
    }


    /*输入违章城市ajax存储*/
    @RequestMapping("/saveregionid")
    @ResponseBody
    public String saveregionid(@RequestParam(name = "regionid",required = false) String regionid,
                               @RequestParam(name = "custcarid",required = false) Long custcarid,Model model)
    {
        ContextStorage storage=new SessionContextStorageImpl(request);
        HttpUserContext userContext=storage.getUserContext("loginuser");

        Integer flag=custcarRepository.saveregionid(regionid,custcarid,userContext.getCustid());
        if(flag>0){
            return "success";
        }else {
            return "fail";
        }
    }
}